package com.yuanjiu.service.jiuxian;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.yuanjiu.dao.yuanjiu.DataMergeDao;
import com.yuanjiu.pojo.yuanjiu.CategoryIdName;
import com.yuanjiu.pojo.yuanjiu.CategoryObject;

import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.ResultItems;
import us.codecraft.webmagic.Site;
import us.codecraft.webmagic.Spider;
import us.codecraft.webmagic.Task;
import us.codecraft.webmagic.pipeline.Pipeline;
import us.codecraft.webmagic.processor.PageProcessor;
import us.codecraft.webmagic.selector.Selectable;

@Service
public class JiuxianBrand{

	@Autowired
	private BrandOutput brandOutput;
	
	public void process(String... a){
		Spider.create(new BrandInput()).addPipeline(brandOutput).addUrl(a).run();
	}
}


class BrandInput implements PageProcessor{
	
	private Site site = Site.me().setTimeOut(5000).setRetryTimes(3).setRetrySleepTime(2);

	@Override
	public void process(Page page) {
		String name = null;
		Set<String> tmpCollection = new HashSet<String>();
		// 白酒
		if (page.getUrl().regex("(http://list.jiuxian.com/1-0-0-0-0-0-0-0-0-0-0-0.htm.*)").match()) {
			name = "白酒";
		}
		// 葡萄酒
		else if (page.getUrl().regex("(http://list.jiuxian.com/2-0-0-0-0-0-0-0-0-0-0-0.htm.*)").match()) {
			name = "葡萄酒";
		}
		// 洋酒
		else if (page.getUrl().regex("(http://list.jiuxian.com/4-0-0-0-0-0-0-0-0-0-0-0.htm.*)").match()) {
			name = "洋酒";
		}
		// 啤酒
		else if (page.getUrl().regex("(http://list.jiuxian.com/151-0-0-0-0-0-0-0-0-0-0-0.htm.*)").match()) {
			name = "啤酒";
		}
		// 黄酒
		else if (page.getUrl().regex("(http://list.jiuxian.com/95-0-0-0-0-0-0-0-0-0-0-0.htm.*)").match()) {
			name = "黄酒";
		}
		// 养生酒
		else if (page.getUrl().regex("(http://list.jiuxian.com/6-0-0-0-0-0-0-0-0-0-0-0.htm.*)").match()) {
			name = "保健酒";
		}
		Selectable xx = page.getHtml().xpath("//div[@id='brandAll']/ul/li");
		java.util.List<Selectable> mm = xx.nodes();
		for (Selectable tmp : mm) {
			//处理显示不全问题（title中有完整名称）
			String brandName=tmp.xpath("/li/a/@title").get();
			if(brandName.equals("")){
				brandName=tmp.xpath("/li/a/text()").get();
			}
			if (!tmpCollection.contains(brandName)) {
				tmpCollection.add(brandName);
			}
		}
		page.putField(name, tmpCollection);
	}

	@Override
	public Site getSite() {
		// TODO Auto-generated method stub
		return site;
	}
}


@Service
class BrandOutput implements Pipeline {

//	@Autowired
//	private CategoryDao categoryDao;
	@Autowired
	private DataMergeDao dataMergeDao;

	@SuppressWarnings("unchecked")
	@Override
	public void process(ResultItems resultItems, Task task) {

		Map<String, Object> result = resultItems.getAll();

		for (Map.Entry<String, Object> tmp : result.entrySet()) {
			List<CategoryIdName> categoryIdNames;
			try {
				//获取所有分类名称，id
				categoryIdNames=dataMergeDao.getCategoryName();
				String cname = tmp.getKey();
				Integer catid = null;
				for(CategoryIdName categoryIdName:categoryIdNames){
					if(categoryIdName.getCat().equals(cname)){
						catid=categoryIdName.getId();
					}
				}
				//0对应其他类别
				if(catid==null){
					catid=0;
				}
				//获取一级分类下所有品牌
				List<String> categoryObjects=dataMergeDao.getCategoriesByParent(catid);
				//抓取到的所有品牌名称
				Set<String> cvalue = (Set<String>) tmp.getValue();
				//"其他"品牌
				cvalue.add("其他");
				//品牌持久化到数据库
				List<CategoryObject> list=new ArrayList<CategoryObject>();
				for (String valuetmp : cvalue) {
					//品牌名称已存在则跳过
					if(categoryObjects.contains(valuetmp)){
						continue;
					}
					CategoryObject categoryObject2 = new CategoryObject();
					categoryObject2.setParent(catid);
					categoryObject2.setName(valuetmp);
					list.add(categoryObject2);
					// 插入分類
				}
				if(list.size()>0){
					dataMergeDao.insertCategory(list); 
				}
			} catch (Exception e1) {
				e1.printStackTrace();
			}
		}
	}
}
